package com.ruoyi.framework.security.provider;

import com.ruoyi.framework.security.token.PhoneAuthToken;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class PhoneAuthProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PhoneAuthToken phoneAuthToken = (PhoneAuthToken) authentication;
        String phone = authentication.getName();
        UserDetails user = userDetailsService.loadUserByUserPhone(phone,phoneAuthToken.getUserType());
        return new PhoneAuthToken(user, user.getPassword(), user.getAuthorities(), phoneAuthToken.getUserType());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return PhoneAuthToken.class.isAssignableFrom(authentication);
    }
}